/*

Copyright (C) 2010 Felix Niessen (felix.niessen@googlemail.com || caendle.de) (Bewicklungsrechner XL)

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.

__________________________________________

Mit bestem dank an:
- overclocker_2001 alias oc2k1 & DrM (drmalte@maltemedia.de) [unbekannter weise da es die email nichtmehr giebt] für den "normalen" bewicklungsrechner.
- Friedhelm S. für die Formeln und die Anleitung zur berechnung des Wickelfaktors
- und alle die mir im RCN geholfen haben :)

*/

//start at dom
var isInit = false;
window.onDomReady = function (fn) {
    if (window.addEventListener) {
        window.addEventListener("DOMContentLoaded", fn, false);
    } else if (window.addEvent) {
        window.addEvent('domready', fn);
    } else {
        document.onreadystatechange = function () {
            if (document.readyState === "interactive" || document.readyState === "loaded" || document.readyState === "complete") {
                !isInit ? fn() : 0;
                isInit = true;
            }
        }
    }
}
window.onDomReady(jsStart);

//for the individual steps
var v = window.location.search.substring(1, location.search.length).split('&');
var getVars = Array();
for (var i = 0; i < v.length; i++) {
    var temp = v[i].split('=');
    getVars[temp[0].toLowerCase()] = temp[1];
}
var act_step = 1;
var slotx = false;
var polex = false;
var diagram_x = false;
var diagram_y = false;
var switching_x = false;
var isSingleLayer = false;
var distributed = false;
var inputIsValid = false;
var SPSselector = document.createElement('select');
var schaltxy = false;
var shorteningValue = 0;
var errorV = false;
var isFractionalDistributed = false;


//Sprachen
var lang = Array();

//Sprachen die zur auswahl stehen
lang[1] = 'de';
lang[2] = 'en';
lang[3] = 'zh';

// Die wörter in den verschiedenen sprachen

lang['slots_de'] = 'Slots';
lang['slots_en'] = 'Slots';
lang['slots_zh'] = '槽数'

lang['pole_de'] = 'Pole';
lang['pole_en'] = 'Magnet Poles';
lang['pole_zh'] = '极数'

lang['berechnen_de'] = 'Berechnen';
lang['berechnen_en'] = 'Calculate';
lang['berechnen_zh'] = '计算'

lang['kgv_de'] = 'KgV';
lang['kgv_en'] = 'LCM';
lang['kgv_zh'] = '最小公倍数';


lang['rastetn1_de'] = 'Diese Nut/Pol kombination rastet voraussichtlich';
lang['rastetn1_en'] = 'This slot/magnet pole combination will have';
lang['rastetn1_zh'] = '这种槽极配合有';

lang['rastetn2_de'] = 'mal pro Umdrehung';
lang['rastetn2_en'] = 'cogging steps per turn';
lang['rastetn2_zh'] = '个转矩波动每圈';

lang['kein_html5_de'] = '<p>Ihr Browser unterstützt kein HTML 5!<br />Grafische Darstellung nicht möglich.</p>';
lang['kein_html5_en'] = '<p>Your browser does not support HTML 5!<br /> graphical representation is not possible. </p>';
lang['kein_html5_zh'] = '<p>你的浏览器不支持HTML 5!<br /> 无法显示图像和动画. </p>';

lang['nut_3_teilbar_de'] = 'Nutanzahl muss durch 3 teilbar sein!';
lang['nut_3_teilbar_en'] = 'Number of slots must be divisible by 3!';
lang['nut_3_teilbar_zh'] = '槽数必须可以被3整除!';

lang['pol_grade_de'] = 'Polanzahl muss gerade sein!';
lang['pol_grade_en'] = 'Number of magnet poles must be divisible by 2!';
lang['pol_grade_zh'] = '极数必须可以被2整除!';

lang['nut_pol_ungleich_de'] = 'Polanzahl muss ungleich Nutanzahl sein!';
lang['nut_pol_ungleich_en'] = 'Magnet pole number and slot number must be different!';
lang['nut_pol_ungleich_zh'] = '槽数和极数必须不相同!';

lang['unausgewogen_de'] = 'Lösung unausgewogen!';
lang['unausgewogen_en'] = 'Unbalanced solution!';
lang['unausgewogen_zh'] = '不平衡的结果！';

lang['schritt_schritt_de'] = 'Schritt für Schritt';
lang['schritt_schritt_en'] = 'Winding animation';
lang['schritt_schritt_zh'] = '绕组动画';


lang['schritt_zurueck_de'] = 'Schritt zurück';
lang['schritt_zurueck_en'] = 'step back';
lang['schritt_zurueck_zh'] = '上一步';


lang['schritt_vor_de'] = 'Nächster schritt';
lang['schritt_vor_en'] = 'next step';
lang['schritt_vor_zh'] = '下一步';

lang['anfang_de'] = 'Anfang';
lang['anfang_en'] = 'Start';
lang['anfang_zh'] = '开始';

lang['ende_de'] = encodeURI('Ende');
lang['ende_en'] = 'End';
lang['ende_zh'] = '结束';

lang['kein_wickelfaktor_de'] = 'Wickelfaktor berechnung nicht möglich. ';
lang['kein_wickelfaktor_en'] = 'Winding factor calculation is not possible.';
lang['kein_wickelfaktor_zh'] = '无法计算绕组因数。';

lang['wickelfaktor_de'] = 'Und hat einen Wickelfaktor von: ';
lang['wickelfaktor_en'] = 'And its winding factor is: ';
lang['wickelfaktor_zh'] = '绕组因数为：';

lang['erweitert_de'] = 'erweitert';
lang['erweitert_en'] = 'advanced';
lang['erweitert_zh'] = '高级选项';

lang['stator_d_de'] = 'Stator Durchmesser:';
lang['stator_d_en'] = 'Stator diameter:';
lang['stator_d_zh'] = '定子直径：';

lang['nut_B_de'] = 'Nut Öffnung:';
lang['nut_B_en'] = 'Slot opening:';
lang['nut_B_zh'] = '槽开口大小：';

lang['nutfaktor_de'] = 'Nutungsfaktor einbeziehen';
lang['nutfaktor_en'] = 'Involving the slot factor';
lang['nutfaktor_zh'] = '相关绕组因数';

lang['einfach_de'] = 'einfach';
lang['einfach_en'] = 'simple';
lang['einfach_zh'] = '简单';

lang['schema_de'] = 'Schema';
lang['schema_en'] = 'Scheme';
lang['schema_zh'] = '设计图';

lang['hammer_leer_de'] = 'für leeren Hammer';
lang['hammer_leer_en'] = 'for empty hammer heads';
lang['hammer_leer_zh'] = 'for empty hammer heads';

lang['teil_motor_de'] = 'um einen Teilmotor abzutrennen';
lang['teil_motor_en'] = 'to seperate a part motor';
lang['teil_motor_zh'] = 'to seperate a part motor';

lang['WF_tabelle_de'] = 'Wickelfaktoren für dieses Bewicklungschema';
lang['WF_tabelle_en'] = 'Winding factors for this winding scheme';
lang['WF_tabelle_zh'] = '这个绕组设计图的绕组因数';

lang['WF_de'] = 'Wickelfaktor';
lang['WF_en'] = 'Winding factor';
lang['WF_zh'] = '绕组因数';

lang['sieheauch_de'] = 'Siehe auch:';
lang['sieheauch_en'] = 'See also:';
lang['sieheauch_zh'] = '参阅：';

lang['Schwankend_de'] = 'Unausgewogen!';
lang['Schwankend_en'] = 'Unbalanced!';
lang['Schwankend_zh'] = '不平衡！';

lang['inTabelle_de'] = 'in die Tabelle';
lang['inTabelle_en'] = 'into the table';
lang['inTabelle_zh'] = '表格中';

lang['schraegung1_de'] = 'Schrägung der Slots';
lang['schraegung1_en'] = 'Skewed slots';
lang['schraegung1_zh'] = '斜槽';

lang['schraegung2_de'] = 'Um wieviel Slots wurde geschrägt';
lang['schraegung2_en'] = 'By how many slots is the skewing';
lang['schraegung2_zh'] = '多少个槽构成斜槽';

lang['Schwankend2_de'] = 'Wickelfaktor Schwankend! Anzeige nicht möglich';
lang['Schwankend2_en'] = 'Winding factor unbalanced! Representation is not possible.';
lang['Schwankend2_zh'] = '绕组因数不平衡，无法显示。';

lang['kuerzung_de'] = "Verkürzung";
lang['kuerzung_en'] = "Shortening";
lang['kuerzung_zh'] = "短距";

lang['schicht_de'] = "schicht";
lang['schicht_en'] = "layer";
lang['schicht_zh'] = "层";

//sprache finden
var selected_lang = 'zh';

let schema = ''

for (i = 1; i < lang.length; i++) {
    if (navigator.userAgent.toLowerCase().indexOf('; ' + lang[i]) !== -1) {
        selected_lang = lang[i];
    }
}

//sprache wechseln
function setlang(id) {
    selected_lang = id;
    jsStart();
}


// Init
var mainContainer = false;

function jsStart() {
    mainContainer = document.getElementById('jsContainer');
    mainContainer.innerHTML = '';
    s_advanced = false;
    isSingleLayer = false;
    var sprachwahl = '<ul>';
    for (i = 1; i < lang.length; i++) {
        if (lang[i].length < 3) {
            if (selected_lang === lang[i]) {
                sprachwahl += '<li id="' + lang[i] + '" onclick="setlang(this.id);" style="color:#0000FF; font-weight:bold;">' + lang[i] + '</li>';
            } else {
                sprachwahl += '<li id="' + lang[i] + '" onclick="setlang(this.id);">' + lang[i] + '</li>';
            }
        }
    }
    sprachwahl += '</ul>';
    var form = ''
    form += '<form style="margin:auto;" name="Windungsrechner" action="javascript:return false;">';
    form += '<label for="Slots" id="slots_t">' + lang['slots_' + selected_lang] + '</label>';
    form += '<input size="3"  maxlength="2" id="Slots" name="Slots" onchange="checkSingleLayerPossibility(true);" />';
    form += '<label for="Pole">' + lang['pole_' + selected_lang] + '</label>';
    form += '<input maxlength="3" size="3" id="Pole" name="Pole" onchange="checkSingleLayerPossibility(true); checkDistributed();" />';
    form += '<span id="schalti"><select id="schalt">';
    form += '<option value="-">D</option>';
    form += '<option value="Y">Y</option>';
    form += '</select></span>';
    form += '<input type="submit" onclick="calculate(); return false;" id="Berechnen" value="' + lang['berechnen_' + selected_lang] + '" />';
    form += '<span id="erweitert_einfach" style=" font-size:12px;" onclick="schema_eingeben();"> &lArr; ' + lang['erweitert_' + selected_lang] + '</span>';
    form += '</form><span id="info"></span>';

    mainContainer.innerHTML += sprachwahl;
    mainContainer.innerHTML += form;
    mainContainer.innerHTML += '<div id="Rasten"></div><div id="nutfacktor"></div><div id ="steps"></div><div id="Ergebnis"></div><div id="canvas_container"></div><div id="link_container"></div>';

    if (getVars['schema'] && getVars['pole'] && isNaN(getVars['schema'])) {
        setTimeout('schema_eingeben()', 20);
        setTimeout('document.Windungsrechner.Slots.value="' + getVars['schema'] + '"', 30);
        setTimeout('document.Windungsrechner.Pole.value="' + getVars['pole'] + '"', 30);
        setTimeout('examineInputAndSchema()', 40);
    } else if (getVars['slots'] && getVars['pole'] && !isNaN(getVars['slots'])) {
        setTimeout('document.Windungsrechner.Slots.value="' + getVars['slots'] + '"', 30);
        setTimeout('document.Windungsrechner.Pole.value="' + getVars['pole'] + '"', 30);
        setTimeout('calculate()', 40);
        setTimeout('checkSingleLayerPossibility(false)', 45);
        setTimeout('checkDistributed()', 50);
    }
}


function checkDistributed() {
    var SlotsCv = document.Windungsrechner.Slots.value;
    var PoleCv = document.Windungsrechner.Pole.value;
    SlotsCv = SlotsCv.replace(/ /g, '');
    var Lochzahl = SlotsCv / 3 / PoleCv;
    var containerCV = document.getElementById('schalti');
    if (!schaltxy) {
        schaltxy = containerCV.innerHTML;
    }
    if (!isNaN(SlotsCv) && !isSingleLayer && Lochzahl >= 1) {
        containerCV.innerHTML = "&nbsp;" + lang['kuerzung_' + selected_lang];
        containerCV.innerHTML += '<input type="text" size="2" maxlength="1" id="verkuerzung" value="' + shorteningValue + '" />';
    } else if (Lochzahl < 1) {
        containerCV.innerHTML = schaltxy;
    } else {
        containerCV.innerHTML = "";
    }
}


//Check if single layer is possible, if so, then there is the choice possible.
function checkSingleLayerPossibility(refresh) {
    var SlotsCx = document.Windungsrechner.Slots.value;
    // var PoleCx = document.Windungsrechner.Pole.value;
    SlotsCx = SlotsCx.replace(/ /g, '');
    console.log("check single layer possibility, slots=" + SlotsCx);
    if (SlotsCx % 2 === 0 && !isNaN(SlotsCx)) {
        SPSselector.name = "SPSsel";
        SPSselector.onchange = function () {
            switchSingleLayer();
        }
        SPSselector.innerHTML = "";
        var SingleLayerOption2 = document.createElement('option');
        SingleLayerOption2.value = "SPS";
        SingleLayerOption2.innerHTML = "1 " + lang['schicht_' + selected_lang];
        var SingleLayerOption1 = document.createElement('option');
        SingleLayerOption1.value = "-";
        SingleLayerOption1.innerHTML = "2 " + lang['schicht_' + selected_lang];
        if (isSingleLayer) {
            SingleLayerOption2.selected = "selected";
            SPSselector.appendChild(SingleLayerOption2);
            SPSselector.appendChild(SingleLayerOption1);
        } else if (!isSingleLayer) {
            SingleLayerOption1.selected = "selected";
            SPSselector.appendChild(SingleLayerOption1);
            SPSselector.appendChild(SingleLayerOption2);
        }
        document.Windungsrechner.insertBefore(SPSselector, document.getElementById('schalti'));
    } else if (document.Windungsrechner.SPSsel) {

        document.Windungsrechner.removeChild(SPSselector);
        if (refresh) {
            isSingleLayer = false;
        } else {
            isSingleLayer = true;
        }
    }

}

function switchSingleLayer() {

    if (document.Windungsrechner.SPSsel.value === "SPS") {
        isSingleLayer = true;
        distributed = false;
        shorteningValue = 0;
        checkDistributed();
    } else if (document.Windungsrechner.SPSsel.value === "-") {
        isSingleLayer = false;
        distributed = false;
        shorteningValue = document.getElementById('verkuerzung').value;
        checkDistributed();
    }
    console.log("is single layer =" + document.Windungsrechner.SPSsel.value);
    console.log(shorteningValue);
}


function examineInputAndSchema() {
    var isSingleLayer = false;
    var schema = document.getElementById('Slots').value.replace(/ /g, '');
    schema = schema.replace(/U/g, 'A');
    schema = schema.replace(/u/g, 'a');
    schema = schema.replace(/V/g, 'B');
    schema = schema.replace(/v/g, 'b');
    schema = schema.replace(/W/g, 'C');
    schema = schema.replace(/w/g, 'c');
    //如果‘|’不存在则不是分布式绕组
    if (schema.indexOf('|') !== -1) {
        distributed = true;
    } else {
        distributed = false;
    }
    //处理分布式绕组
    if (distributed) {
        distributed = schema;
        var nutcount = schema.split('|');
        schema = "";
        for (i = 0; i < nutcount.length; i++) {
            schema = schema + "-";
        }
        schema = schema.replace(/\|/g, '').replace(/a/g, '').replace(/b/g, '').replace(/c/g, '');
    }
    //如果‘-”不存在，则isSingleLayer=true
    schema.indexOf('-') !== -1 ? isSingleLayer = true : 0;
    if (schema[0] === '-' && schema[schema.length - 1] === '-') {
        schema = schema.substr(1);
    } else if (schema[0] !== '-' && schema[schema.length - 1] !== '-' && isSingleLayer && schema.length % 3 !== 0) {
        schema = schema + '-';
    }
    var schema_y = schema;
    schema = schema.replace(/\//g, '');
    var Slots = schema.length;
    var Pole = document.getElementById('Pole').value;
    if (Slots % 3 !== 0 || Slots < 3) {
        document.getElementById('Ergebnis').innerHTML = lang['nut_3_teilbar_' + selected_lang];
        document.Windungsrechner.Slots.focus();
        document.Windungsrechner.Slots.select();
        blink(document.Windungsrechner.Slots.id);
        clear();
        return;
    }

    if (Pole % 2 !== 0 || Pole < 2) {
        document.getElementById('Ergebnis').innerHTML = lang['pol_grade_' + selected_lang];
        document.Windungsrechner.Pole.focus();
        document.Windungsrechner.Pole.select();
        blink(document.Windungsrechner.Pole.id);
        clear();
        return;
    }

    if (Pole === Slots) {
        document.getElementById('Ergebnis').innerHTML = lang['nut_pol_ungleich_' + selected_lang];
        document.Windungsrechner.Pole.focus();
        document.Windungsrechner.Pole.select();
        blink(document.Windungsrechner.Pole.id);
        clear();
        return;
    }
    inputIsValid = true;
    Schema_output(Slots, Pole, schema, false, isSingleLayer, schema_y);
}

function shiftcycle(s, n) {
    n = n % s.length;
    var a = s.split("");
    var left = a.splice(0, n);
    return a.concat(left).join("");
}


// Color scheme, calculate KgV
function Schema_output(slots, pole, schema, _error, SPS, schema_y, bothlayers) {
    slotx = slots;
    diagram_x = schema;
    diagram_y = schema_y;
    polex = pole;
    s_advanced = false;
    var results = document.getElementById('Ergebnis');
    var colored_result = '';

    //Buchstaben färben
    //Color letters
    if (!distributed) {
        for (y = 0; y < schema_y.length; y++) {
            text_color = color_too(schema_y[y]);
            colored_result += '<span id="s_' + (y + 1) + '" style="color:' + text_color + ';">' + schema_y[y] + '</span>';
        }
    } else {
        var ohnestator = distributed.replace(/\|/g, '');
        for (i = 0; i < ohnestator.length; i++) {
            if (ohnestator[0] === ohnestator[ohnestator.length - 1]) {
                var zwischen_Z = ohnestator[ohnestator.length - 1];
                ohnestator = zwischen_Z + ohnestator.substring(0, ohnestator.length - 1);
            } else {
                break;
            }
        }
        distributed = "";
        for (i = 0; i < ohnestator.length; i++) {
            distributed += ohnestator[i] + '|';
        }
        if (!isSingleLayer && !inputIsValid) {
            var ZweiSchichtV = "";
            for (y = 0; y < distributed.length; y++) {
                if (distributed[y] !== '|' && distributed[y] !== '/' && distributed[y] !== '-') {
                    ZweiSchichtV += distributed[y] + distributed[y];
                } else {
                    ZweiSchichtV += distributed[y];
                }
            }
            distributed = ZweiSchichtV;
        }
        for (y = 0; y < distributed.length; y++) {
            text_color = color_too(distributed[y]);
            colored_result += '<span id="s_' + (y + 1) + '" style="color:' + text_color + ';">' + distributed[y] + '</span>';
        }
    }
    // Shortening
    if (document.getElementById('verkuerzung') && !isNaN(document.getElementById('verkuerzung').value) && !isSingleLayer && distributed) {
        shorteningValue = document.getElementById('verkuerzung').value;
        console.log("shortening = " + shorteningValue);
        var nutbelag_xx = distributed.split('|');
        var first_layer = "";
        var second_layer = "";
        for (i = 0; i < nutbelag_xx.length - 1; i++) {
            first_layer += nutbelag_xx[i][1];
            second_layer += nutbelag_xx[i][0];
        }
        var redistributed = "";
        // 这里处理shortening
        first_layer = shiftcycle(first_layer, shorteningValue)
        for (i = 0; i < nutbelag_xx.length - 1; i++) {
            redistributed += first_layer[i] + second_layer[i] + '|';
        }
        distributed = redistributed;
        if (bothlayers) {
            distributed = bothlayers
        }
        colored_result = "";
        for (y = 0; y < distributed.length; y++) {
            text_color = color_too(distributed[y]);
            colored_result += '<span id="s_' + (y + 1) + '" style="color:' + text_color + ';">' + distributed[y] + '</span>';
        }
    }
    //如果不是分布式绕组
    if (!distributed) {
        var schritt_div = document.getElementById('steps');
        schritt_div.innerHTML = "<span></span>";
        schritt_div.firstChild.innerHTML = lang['schritt_schritt_' + selected_lang];
        schritt_div.firstChild.onclick = function () {
            schritt_fur_schritt();
        }
        act_step = 1;
    } else {
        document.getElementById('steps').innerHTML = '';
    }


    if (_error) {
        results.innerHTML = _error + "( " + colored_result + " )";
        errorV = true;
    } else {
        results.innerHTML = colored_result;
        errorV = false;
    }
    //KgV errechnen
    var KgV = false;
    a = slots;
    b = pole;
    x = a;
    y = b;

    while (x < y || x > y) {
        if (x - y < 0) {
            x = x * 1 + a * 1;
        } else {
            y = y * 1 + b * 1;
        }

    }
    KgV = x;

    document.getElementById('Rasten').innerHTML = lang['rastetn1_' + selected_lang] + ' <span style="font-weight:bold;">' + KgV + '</span> ' + lang['rastetn2_' + selected_lang] + '. <span style="font-size:10px; color:#999; font-style:italic;">' + lang['kgv_' + selected_lang] + '(' + slots + ',' + pole + ')</span>';
    document.getElementById('Rasten').style.borderBottom = "1px solid #000";
    if (document.getElementById('schalt')) {
        var schaltung = document.getElementById('schalt').value;
    } else {
        var schaltung = '-';
    }
    schaltung === '-' ? schaltung = false : 0;

    switching_x = schaltung;
    drawStator(slots, schema_y, false, schaltung);

}

function color_too(buchstabe) {
    var farbe = '#00CA00';
    buchstabe = buchstabe.toLowerCase();
    if (buchstabe === '|') {
        farbe = '#000000';
    }
    if (buchstabe === '/') {
        farbe = '#000000';
    }
    if (buchstabe === '-') {
        farbe = '#000000';
    }
    if (buchstabe === 'a') {
        farbe = '#EA0000';
    }
    if (buchstabe === 'b') {
        farbe = '#008AE6';
    }
    if (buchstabe === 'c') {
        farbe = '#00CA00';
    }
    return farbe;
}


// Draw stator and winding in canvas
function drawStator(slots, schema, step, Y_D) {
    var xzx = schema.split('/').length - 1
    !step ? step = slots + 1 + xzx : 0;

    if (schema[step - 1] === '/') {
        step = step - 1;
    }


    //// Create and customize canvas element
    var canvas_container = document.getElementById('canvas_container');

    if (document.getElementById("statorCanvas")) {
        canvas_container.removeChild(document.getElementById("statorCanvas"));
    }

    var statorCanvas = document.createElement('canvas');
    statorCanvas.id = "statorCanvas";
    statorCanvas.height = "1200";
    statorCanvas.width = "1200";
    var canvas_mid = 600;
    statorCanvas.innerHTML = lang['kein_html5_' + selected_lang];
    canvas_container.appendChild(statorCanvas);

    var statorPainter = statorCanvas.getContext('2d');

    //Grundlegende hammer Maße
    // Basic hammer dimensions
    let hammerHeight = 255;
    let hammerWidth = 950;
    hammerWidth = hammerWidth / slots;
    hammerHeight = hammerHeight - (slots / 3);
    if (slots === 6) {
        hammerWidth = hammerWidth + 3;
    } else if (slots === 3) {
        hammerWidth = hammerWidth - 80;
    }


    // Inner circle of the stator
    // statorPainter.fillStyle = "rgb(186,186,186)";
    // statorPainter.beginPath();
    // statorPainter.arc(canvas_mid, canvas_mid, 148, 0, Math.PI * 2, true);
    // statorPainter.closePath();
    // statorPainter.fill();

    statorPainter.fillStyle = "#FFF";
    statorPainter.beginPath();
    statorPainter.arc(canvas_mid, canvas_mid, 112, 0, Math.PI * 2, true);
    statorPainter.closePath();
    statorPainter.fill();


    // height of the interconnection
    var s_basis = 100;

    if (slots > 21 && slots <= 36) {
        s_basis = s_basis + (slots / 3.8);
    }

    // ebenen der verschaltung
    // levels of interconnection
    var ebene = Array();
    ebene['a1'] = 40 + s_basis;
    ebene['a2'] = 35 + s_basis;
    ebene['b1'] = 30 + s_basis;
    ebene['b2'] = 25 + s_basis;
    ebene['c1'] = 20 + s_basis;
    ebene['c2'] = 15 + s_basis;

    // move stator to center
    statorPainter.translate(canvas_mid, canvas_mid);


    // draw teeth
    for (var i = 0; i < slots; i++) {

        // draw teeth
        statorPainter.beginPath();
        statorPainter.moveTo(130, hammerWidth / 4);
        statorPainter.lineTo(Math.round(hammerHeight / 1.03), hammerWidth / 4);
        statorPainter.lineTo(Math.round(hammerHeight / 1.03), -hammerWidth / 4);
        statorPainter.lineTo(130, -hammerWidth / 4);
        statorPainter.textBaseline = 'middle';

        statorPainter.fillStyle = "rgb(186,186,186)";
        statorPainter.fill();
        // turn to the next one
        statorPainter.rotate(Math.PI / (slots / 2));
    }
    // stator.rotate(Math.PI / (slots / 2) / 2);
    statorPainter.fillStyle = "#111";

    var Swikel = schema.substr(0, step).split('/');


    var Sschemen = schema.split('/');
    var schemen = Array();
    for (i = 0; i < Swikel.length; i++) {
        schemen[i] = Sschemen[i];
    }
    var gesamtlength = -1;
    for (zx = 0; zx < schemen.length; zx++) {
        schema = schemen[zx];

        //Anfäng und enden merken
        // Remember beginnings and ends
        var f_u = Array();
        f_u['a'] = false;
        f_u['b'] = false;
        f_u['c'] = false;

        //Verlauf der ebenen
        // Course of the levels
        ebenen_verlauf = Array();
        ebenen_verlauf['a1'] = false;
        ebenen_verlauf['a2'] = false;
        ebenen_verlauf['b1'] = false;
        ebenen_verlauf['b2'] = false;
        ebenen_verlauf['c1'] = false;
        ebenen_verlauf['c2'] = false;

        // Y and D connection
        var enden = Array();
        enden[0] = 0;
        enden[3] = 'abc';
        var das_nicht = false;
        var erstefarbe = false;


        for (var i = 0; i < schema.length; i++) {
            gesamtlength = gesamtlength + 1;
            if ((gesamtlength + 1 + zx) <= step) {
                // Bewicklung und verschaltung
                // winding and interconnection
                var wire_color = color_too(schema[i]);

                var richtung = 15;
                if (schema[i].toLowerCase() === schema[i]) {
                    richtung = -15;
                }
                var abc = 'abc';

                // Bewicklung
                // wrapping
                var schon_beschriftet = false;
                for (var y = 0; y < 75; y = y + 15) {
                    das_nicht = false;
                    if (schema[i].toLowerCase() !== '-') {
                        console.log("not -")
                        statorPainter.beginPath();
                        //nur bis zum bestimmten step bewickeln
                        // only wrap up to the given step
                        if (richtung === 15) {
                            //Lienie in richtung 1
                            statorPainter.moveTo(156 + y, (hammerWidth / 4) + 2);
                            statorPainter.lineTo(156 + y + richtung, -(hammerWidth / 4) - 2);

                            if (y === 0) {
                                // Anfangs punkt richtung 1
                                statorPainter.moveTo(156 + y, -(hammerWidth / 4) + 2);
                                statorPainter.lineTo(156 + y, -(hammerWidth / 4) - 2);

                                if (!f_u[schema[i].toLowerCase()]) {
                                    // wenns die erste spule einer fase in richtung 1 ist anfang malen
                                    f_u[schema[i].toLowerCase()] = schema.toLowerCase().lastIndexOf(schema[i].toLowerCase());
                                    statorPainter.moveTo(156 + y, -(hammerWidth / 4) + 2);
                                    statorPainter.lineTo(156 + y, -(hammerWidth / 3.5) - 5);
                                    statorPainter.moveTo(154 + y, -(hammerWidth / 3.5) - 5);
                                    statorPainter.lineTo(300, -(hammerWidth / 3.5) - 5);
                                    statorPainter.font = "bold 24px 'verdana'";
                                    statorPainter.fillText && slots !== 3 ? statorPainter.fillText(decodeURI(lang['anfang_' + selected_lang]) + ' ' + schema[i].toUpperCase(), 275, 0) : 0;
                                    schon_beschriftet = true;

                                    ebenen_verlauf[schema[i].toLowerCase() + '1'] = false;
                                    ebenen_verlauf[schema[i].toLowerCase() + '2'] = false;
                                } else {
                                    // anfang einer spule in richtung 1 aus verschaltung
                                    if (ebenen_verlauf[schema[i].toLowerCase() + '1']) {
                                        var sub_e = '1';
                                    } else if (ebenen_verlauf[schema[i].toLowerCase() + '2']) {
                                        var sub_e = '2';
                                    } else {
                                        var sub_e = '1';
                                    }
                                    ebenen_verlauf[schema[i].toLowerCase() + sub_e] = true;
                                    statorPainter.moveTo(156 + y, -(hammerWidth / 4.3) - 2);
                                    statorPainter.lineTo(ebene[schema[i].toLowerCase() + sub_e] - (18 / slots), -(hammerWidth / 4.3) - 2);

                                    //ende spule oben links
                                    statorPainter.arc(0, 0, ebene[schema[i].toLowerCase() + sub_e], (-Math.PI / slots) + 0.001, -Math.PI / slots, true);


                                }
                            }
                            if (y === 60) {
                                // Ende richtung 1
                                statorPainter.moveTo(171 + y, (hammerWidth / 4) + 2);
                                statorPainter.lineTo(171 + y, (hammerWidth / 4) - 2);

                                if (i === f_u[schema[i].toLowerCase()]) {
                                    // wenns die lätzte spule einer fase in richtung 1 ist ende malen
                                    if (!Y_D) {
                                        statorPainter.moveTo(171 + y, (hammerWidth / 4) - 2);
                                        statorPainter.lineTo(300, (hammerWidth / 4) - 2);
                                        statorPainter.font = "16px 'verdana'";
                                        statorPainter.fillText && !schon_beschriftet ? statorPainter.fillText(lang['ende_' + selected_lang] + ' ' + schema[i].toUpperCase(), 275, 0) : 0;
                                    } else if (Y_D === 'Y') {
                                        das_nicht = true;
                                        statorPainter.moveTo(171 + y, (hammerWidth / 4.5) - 2);
                                        statorPainter.lineTo(171 + y, (hammerWidth / 4) + 5);

                                        statorPainter.moveTo(171 + y, (hammerWidth / 4) + 5);
                                        statorPainter.lineTo(148, (hammerWidth / 4) + 5);
                                        enden[1] = schema[i].toLowerCase();
                                        switch (enden[0]) {
                                            case(0):
                                                enden[0] = 1;
                                                statorPainter.arc(0, 0, 100, Math.PI / slots, (Math.PI / slots) + 0.001, false);
                                                erstefarbe = schema[i].toLowerCase();
                                                break;
                                            case(1):
                                                statorPainter.lineTo(100, 0);
                                                enden[0] = 2;
                                                das_nicht = 'mitte';
                                                statorPainter.moveTo(100, 0);
                                                statorPainter.lineTo(90, 0);
                                                break;
                                            case(2):
                                                enden[0] = 3;
                                                statorPainter.arc(0, 0, 100, (-Math.PI / slots) + 0.001, -Math.PI / slots, true);
                                                break;
                                        }
                                    }

                                    ebenen_verlauf[schema[i].toLowerCase() + '1'] = false;
                                    ebenen_verlauf[schema[i].toLowerCase() + '2'] = false;
                                } else {

                                    // ende einer spule in richtung 1 zu verschaltung
                                    if (!ebenen_verlauf[schema[i].toLowerCase() + '1']) {
                                        var sub_e = '1';
                                        ebenen_verlauf[schema[i].toLowerCase() + '2'] = false;
                                    } else if (!ebenen_verlauf[schema[i].toLowerCase() + '2']) {
                                        var sub_e = '2';
                                        ebenen_verlauf[schema[i].toLowerCase() + '1'] = false;
                                    }
                                    ebenen_verlauf[schema[i].toLowerCase() + sub_e] = true;
                                    // ende einer spule rechts
                                    statorPainter.moveTo(171 + y, (hammerWidth / 4.5) - 2);
                                    statorPainter.lineTo(171 + y, (hammerWidth / 4) + 5);

                                    statorPainter.moveTo(171 + y, (hammerWidth / 4) + 5);
                                    statorPainter.lineTo(ebene[schema[i].toLowerCase() + sub_e] - (18 / slots), (hammerWidth / 4) + 5);

                                    //ende spule oben rechts
                                    statorPainter.arc(0, 0, ebene[schema[i].toLowerCase() + sub_e], Math.PI / slots, (Math.PI / slots) + 0.001, false);
                                }
                            }

                        } else {
                            //Lienie in richtung 2
                            statorPainter.moveTo(171 + y, (hammerWidth / 4) + 2);
                            statorPainter.lineTo(171 + y + richtung, -(hammerWidth / 4) - 2);

                            if (y === 0) {
                                // Anfangs punkt richtung 2
                                // line towards 2
                                statorPainter.moveTo(156 + y, (hammerWidth / 4) + 2);
                                statorPainter.lineTo(156 + y, (hammerWidth / 4) - 2);
                                if (!f_u[schema[i].toLowerCase()]) {
                                    // wenns die erste spule einer fase in richtung 2 ist anfang malen
                                    f_u[schema[i].toLowerCase()] = schema.toLowerCase().lastIndexOf(schema[i].toLowerCase());
                                    statorPainter.moveTo(156 + y, (hammerWidth / 4) + 2);
                                    statorPainter.lineTo(156 + y, (hammerWidth / 3.5) + 5);
                                    statorPainter.moveTo(154 + y, (hammerWidth / 3.5) + 5);
                                    statorPainter.lineTo(300, (hammerWidth / 3.5) + 5);
                                    statorPainter.font = "bold 24px 'verdana'";
                                    statorPainter.fillText && slots !== 3 ? statorPainter.fillText(decodeURI(lang['anfang_' + selected_lang]) + ' ' + schema[i].toUpperCase(), 275, 0) : 0;
                                    schon_beschriftet = true;

                                    ebenen_verlauf[schema[i].toLowerCase() + '1'] = false;
                                    ebenen_verlauf[schema[i].toLowerCase() + '2'] = false;
                                } else {
                                    // anfang einer spule in richtung 2 aus verschaltung
                                    if (ebenen_verlauf[schema[i].toLowerCase() + '1']) {
                                        var sub_e = '1';
                                    } else if (ebenen_verlauf[schema[i].toLowerCase() + '2']) {
                                        var sub_e = '2';
                                    } else {
                                        var sub_e = '1';
                                    }
                                    ebenen_verlauf[schema[i].toLowerCase() + sub_e] = true;
                                    statorPainter.moveTo(156 + y, (hammerWidth / 4.5) + 3);
                                    statorPainter.lineTo(ebene[schema[i].toLowerCase() + sub_e] - (18 / slots), (hammerWidth / 4.5) + 2);

                                    statorPainter.lineTo(ebene[schema[i].toLowerCase() + sub_e], 0);
                                    statorPainter.arc(0, 0, ebene[schema[i].toLowerCase() + sub_e], 0, -Math.PI / slots, true);

                                }
                            }
                            if (y === 60) {
                                // Ende richtung 2
                                statorPainter.moveTo(171 + y, -(hammerWidth / 4) + 2);
                                statorPainter.lineTo(171 + y, -(hammerWidth / 4) - 2);

                                if (i === f_u[schema[i].toLowerCase()]) {
                                    // wenns die lätzte spule einer fase in richtung 2 ist ende malen
                                    if (!Y_D) {
                                        statorPainter.moveTo(171 + y, -(hammerWidth / 4));
                                        statorPainter.lineTo(300, -(hammerWidth / 4));
                                        statorPainter.font = "16px 'verdana'";
                                        statorPainter.fillText && !schon_beschriftet ? statorPainter.fillText(lang['ende_' + selected_lang] + ' ' + schema[i].toUpperCase(), 275, 0) : 0;
                                    } else if (Y_D === 'Y') {
                                        das_nicht = true;
                                        statorPainter.moveTo(171 + y, -(hammerWidth / 4.5) + 2);
                                        statorPainter.lineTo(171 + y, -(hammerWidth / 4) - 5);

                                        statorPainter.moveTo(171 + y, -(hammerWidth / 4) - 5);
                                        statorPainter.lineTo(148, -(hammerWidth / 4) - 5);
                                        enden[1] = schema[i].toLowerCase();
                                        switch (enden[0]) {
                                            case(0):
                                                enden[0] = 1;
                                                statorPainter.arc(0, 0, 100, Math.PI / slots, (Math.PI / slots) + 0.001, false);
                                                erstefarbe = schema[i].toLowerCase();
                                                break;
                                            case(1):
                                                statorPainter.lineTo(100, 0);
                                                enden[0] = 2;
                                                das_nicht = 'mitte';
                                                statorPainter.moveTo(100, 0);
                                                statorPainter.lineTo(90, 0);
                                                break;
                                            case(2):
                                                enden[0] = 3;
                                                statorPainter.arc(0, 0, 100, (-Math.PI / slots) + 0.001, -Math.PI / slots, true);
                                                break;
                                        }
                                    }

                                    ebenen_verlauf[schema[i].toLowerCase() + '1'] = false;
                                    ebenen_verlauf[schema[i].toLowerCase() + '2'] = false;
                                } else {
                                    // ende einer spule in richtung 1 zu verschaltung
                                    if (!ebenen_verlauf[schema[i].toLowerCase() + '1']) {
                                        var sub_e = '1';
                                        ebenen_verlauf[schema[i].toLowerCase() + '2'] = false;
                                    } else if (!ebenen_verlauf[schema[i].toLowerCase() + '2']) {
                                        var sub_e = '2';
                                        ebenen_verlauf[schema[i].toLowerCase() + '1'] = false;
                                    }

                                    ebenen_verlauf[schema[i].toLowerCase() + sub_e] = true;
                                    statorPainter.moveTo(171 + y, -(hammerWidth / 4.5) + 2);
                                    statorPainter.lineTo(171 + y, -(hammerWidth / 4) - 5);

                                    statorPainter.moveTo(171 + y, -(hammerWidth / 4) - 5);
                                    statorPainter.lineTo(ebene[schema[i].toLowerCase() + sub_e] - (18 / slots), -(hammerWidth / 4) - 5);

                                    statorPainter.moveTo(ebene[schema[i].toLowerCase() + sub_e] - (18 / slots), -(hammerWidth / 4) - 5);

                                    statorPainter.lineTo(ebene[schema[i].toLowerCase() + sub_e], 0);
                                    statorPainter.arc(0, 0, ebene[schema[i].toLowerCase() + sub_e], 0, (Math.PI / slots) + 0.001, false);

                                }
                            }
                        }


                        statorPainter.strokeStyle = wire_color;


                        statorPainter.lineWidth = 4;
                        if (slots > 42) {
                            statorPainter.lineWidth = 2;
                        }
                        if (slots > 24 && slots <= 42) {
                            statorPainter.lineWidth = 3;
                        }

                        statorPainter.stroke();

                    }

                }

                //sternpunkt
                // start point
                if (!das_nicht || das_nicht === 'mitte') {

                    if (das_nicht !== 'mitte') {
                        statorPainter.beginPath();
                        switch (enden[0]) {
                            case(1):
                                statorPainter.arc(0, 0, 100, -Math.PI / slots, Math.PI / slots, false);
                                statorPainter.strokeStyle = color_too(enden[1]);
                                break;
                            case(2):
                                statorPainter.arc(0, 0, 100, Math.PI / slots, -Math.PI / slots, true);
                                statorPainter.strokeStyle = color_too(enden[3]);
                                break;
                        }
                        statorPainter.stroke();
                        enden[3] = enden[3].replace(enden[1], '');
                    } else {
                        statorPainter.beginPath();
                        statorPainter.arc(0, 0, 100, -Math.PI / slots, 0, false);
                        statorPainter.moveTo(100, -4);
                        statorPainter.lineTo(90, -4);
                        statorPainter.strokeStyle = color_too(erstefarbe);
                        statorPainter.stroke();

                        statorPainter.beginPath();
                        statorPainter.arc(0, 0, 100, Math.PI / slots, 0, true);
                        statorPainter.moveTo(100, 4);
                        statorPainter.lineTo(90, 4);
                        var farbe2 = abc.replace(erstefarbe, '').replace(enden[1], '');
                        statorPainter.strokeStyle = color_too(farbe2);
                        statorPainter.stroke();
                        enden[3] = enden[3].replace(enden[1], '');
                    }

                } else {

                }

                // Continue on the way to the next coil
                for (z = 1; z < 3; z++) {
                    for (x = 0; x < abc.length; x++) {
                        if (ebenen_verlauf[abc[x] + z] && abc[x] !== schema[i].toLowerCase()) {

                            statorPainter.beginPath();

                            statorPainter.arc(0, 0, ebene[abc[x] + z], Math.PI / slots, -Math.PI / slots, true);
                            statorPainter.strokeStyle = color_too(abc[x]);
                            statorPainter.stroke();
                        }
                    }
                }


                //Number the hammers
                statorPainter.font = "18px 'verdana'";
                if (slots <= 6) {
                    statorPainter.fillText ? statorPainter.fillText(i + 1, hammerHeight + 15, 0) : 0;
                } else {
                    statorPainter.fillText ? statorPainter.fillText(i + 1, hammerHeight + 8, 0) : 0;
                }


                // turn to the next one
                statorPainter.rotate(-Math.PI / (slots / 2));

            }

        }
        // stator.rotate(-Math.PI / (slots / 2) / 2);
    }
    //如果是分布式绕组就加入一个长的图
    if (distributed) {
        drawWindingLayout(distributed, slots);
    } else {
        if (document.getElementById("statorCanvas2")) {
            mainContainer.removeChild(document.getElementById("statorCanvas2"));
        }
    }
}

// 画winding layout图
// 这里指的是下面的连线图，对于部分设计有bug
function drawWindingLayout(verteiltW, slots) {
    var statorCanvas = document.getElementById("statorCanvas");
    var vertW = statorCanvas.getContext('2d');
    var Nutbelag = verteiltW.split('|');
    var NutCount = Nutbelag.length - 1;

    vertW.rotate((270 * Math.PI / 180) - Math.PI / (NutCount / 2));

    for (y = 0; y < 2; y++) {
        if (Nutbelag[0][y]) {
            vertW.rotate((Math.PI / (NutCount / 2)) / 2);
            for (i = 0; i < slots; i++) {
                vertW.beginPath();
                vertW.lineWidth = 4;
                if (y === 0) {
                    if (Nutbelag[0][1]) {
                        var radiusx = 170;
                    } else {
                        var radiusx = 200;
                    }
                } else {
                    var radiusx = 222;
                }
                let circle_r = 10;
                vertW.font = "20px 'verdana'";
                if (slots > 60) {
                    circle_r = 5;
                    vertW.lineWidth = 2;
                }
                // 这里修改分布式绕组圆圈位置
                vertW.arc(0, radiusx - 4, circle_r, 0.001, 0, false);
                vertW.strokeStyle = color_too(Nutbelag[i][y].toLowerCase());

                // 这里修改分布式绕组正负号位置
                if (Nutbelag[i][y] === Nutbelag[i][y].toLowerCase()) {
                    vertW.fillText ? vertW.fillText('-', -4, radiusx - 2) : 0;
                } else {
                    vertW.fillText ? vertW.fillText('+', -8, radiusx - 2) : 0;
                }

                vertW.stroke();
                vertW.rotate(Math.PI / (NutCount / 2));
            }
            vertW.rotate(-(Math.PI / (NutCount / 2)) / 2);
        }
    }
    if (document.getElementById("statorCanvas2")) {
        mainContainer.removeChild(document.getElementById("statorCanvas2"));
    }
    if (errorV) {
        return;
    }
    var xzBelag = distributed.split('|');
    var windingCanvas = document.createElement('canvas');
    windingCanvas.id = "statorCanvas2";
    windingCanvas.height = (50 * xzBelag.length - 2);
    windingCanvas.width = "700";
    windingCanvas.innerHTML = lang['kein_html5_' + selected_lang];
    mainContainer.appendChild(windingCanvas);

    var windingConnection = windingCanvas.getContext('2d');


    var startposTop = 50;
    var startposLeft = 325;

    var abstand = (slots / polex) - shorteningValue;
    if (isFractionalDistributed) {
        console.log(slots / polex);
        abstand = (slots / polex) - 1.5;
    }
    var schaltbreite = abstand * 40;
    if (schaltbreite > 350) {
        schaltbreite = 350;
    }
    if (schaltbreite < 100) {
        schaltbreite = 100;
    }

    //for one shift
    const slots_per_phase_per_pole = (slots / polex) / 3;
    if (!xzBelag[0][1] && slots_per_phase_per_pole % 2 === 0 && slots_per_phase_per_pole !== 1) {
        abstand = abstand - (slots_per_phase_per_pole / 2);
    }
    var counter = Array();
    counter['a'] = 0;
    counter['b'] = 0;
    counter['c'] = 0;


    for (i = 0; i < xzBelag.length - 1; i++) {

        windingConnection.fillStyle = "rgb(0, 0, 0)";
        windingConnection.fillRect(startposLeft, startposTop, 50, 25);
        windingConnection.fillStyle = "rgb(255, 255, 255)";
        windingConnection.font = "16px 'verdana'";
        if (i > 8) {
            windingConnection.fillText ? windingConnection.fillText(i + 1, startposLeft + 15, startposTop + 18) : 0;
        } else {
            windingConnection.fillText ? windingConnection.fillText(i + 1, startposLeft + 20, startposTop + 18) : 0;
        }
        // 开始画每个槽，这里是双层绕组
        for (z = 0; z < 2; z++) {
            if (xzBelag[i][z]) {
                if (z === 0) {
                    if (xzBelag[i][1]) {
                        var topposV = startposTop - 17;
                    } else {
                        var topposV = startposTop - 12;
                    }
                } else {
                    var topposV = startposTop - 8;
                }
                windingConnection.lineWidth = 3;
                windingConnection.beginPath();
                windingConnection.moveTo(startposLeft, topposV);
                windingConnection.lineTo(startposLeft + 50, topposV);
                if (xzBelag[i][z] !== xzBelag[i][z].toLowerCase()) {
                    windingConnection.moveTo(startposLeft + 32, topposV - 4);
                    windingConnection.lineTo(startposLeft + 38, topposV);
                    windingConnection.moveTo(startposLeft + 32, topposV + 4);
                    windingConnection.lineTo(startposLeft + 38, topposV);
                } else {
                    windingConnection.moveTo(startposLeft + 18, topposV - 4);
                    windingConnection.lineTo(startposLeft + 12, topposV);
                    windingConnection.moveTo(startposLeft + 18, topposV + 4);
                    windingConnection.lineTo(startposLeft + 12, topposV);
                }
                if (xzBelag[i][1]) {
                    if (z === 0) {
                        windingConnection.moveTo(startposLeft + 50, topposV);
                        windingConnection.lineTo(startposLeft + schaltbreite, topposV - (((abstand * 50) - 9) / 2));

                        windingConnection.moveTo(startposLeft, topposV);
                        windingConnection.lineTo(startposLeft - schaltbreite + 50, topposV - (((abstand * 50) - 9) / 2));
                    } else {
                        windingConnection.moveTo(startposLeft + 50, topposV);
                        windingConnection.lineTo(startposLeft + schaltbreite, topposV + (((abstand * 50) - 9) / 2));

                        windingConnection.moveTo(startposLeft, topposV);
                        windingConnection.lineTo(startposLeft - schaltbreite + 50, topposV + (((abstand * 50) - 9) / 2));

                    }
                } else {
                    if (slots_per_phase_per_pole % 2 === 0 && slots_per_phase_per_pole !== 1) {
                        if (counter[xzBelag[i][z].toLowerCase()] >= slots_per_phase_per_pole / 2) {
                            windingConnection.moveTo(startposLeft + 50, topposV);
                            windingConnection.lineTo(startposLeft + schaltbreite, topposV + ((abstand * 50) / 2));

                            windingConnection.moveTo(startposLeft, topposV);
                            windingConnection.lineTo(startposLeft - schaltbreite + 50, topposV + ((abstand * 50) / 2));
                        } else {
                            windingConnection.moveTo(startposLeft + 50, topposV);
                            windingConnection.lineTo(startposLeft + schaltbreite, topposV - ((abstand * 50) / 2));

                            windingConnection.moveTo(startposLeft, topposV);
                            windingConnection.lineTo(startposLeft - schaltbreite + 50, topposV - ((abstand * 50) / 2));
                        }
                        counter[xzBelag[i][z].toLowerCase()]++
                        if (counter[xzBelag[i][z].toLowerCase()] === slots_per_phase_per_pole) {
                            counter[xzBelag[i][z].toLowerCase()] = 0;
                        }
                    } else {
                        if (xzBelag[i][z] !== xzBelag[i][z].toLowerCase()) {
                            windingConnection.moveTo(startposLeft + 50, topposV);
                            windingConnection.lineTo(startposLeft + schaltbreite, topposV + ((abstand * 50) / 2));

                            windingConnection.moveTo(startposLeft, topposV);
                            windingConnection.lineTo(startposLeft - schaltbreite + 50, topposV + ((abstand * 50) / 2));
                        } else {
                            windingConnection.moveTo(startposLeft + 50, topposV);
                            windingConnection.lineTo(startposLeft + schaltbreite, topposV - ((abstand * 50) / 2));

                            windingConnection.moveTo(startposLeft, topposV);
                            windingConnection.lineTo(startposLeft - schaltbreite + 50, topposV - ((abstand * 50) / 2));
                        }
                    }
                }

                windingConnection.strokeStyle = color_too(xzBelag[i][z].toLowerCase());
                windingConnection.stroke();
            }
        }
        startposTop = startposTop + 50;
    }

}


function blink(id) {
    var input = document.getElementById(id);
    input.style.backgroundColor = "#E7796D";
    const handler1 = 'document.getElementById("' + id + '").style.backgroundColor="#FFF"';
    setTimeout(handler1, 500);
}

function clear() {
    if (document.getElementById('Rasten')) {
        document.getElementById('Rasten').innerHTML = '';
    }
    if (document.getElementById('steps')) {
        document.getElementById('canvas_container').removeChild(document.getElementById("statorCanvas"));
        document.getElementById('steps').innerHTML = '';
    }
    if (document.getElementById("statorCanvas2")) {
        mainContainer.removeChild(document.getElementById("statorCanvas2"));
    }
    if (document.getElementById('advanced')) {
        document.getElementById('advanced').innerHTML = "";
    }
    if (document.getElementById('special')) {
        document.getElementById('nutfacktor').innerHTML = '';
    }

}


// ===================================================================================================================== Bewicklungsrechner von POWERCROCO.DE ================================================================================================================
//	(C) 2004 overclocker_2001 alias oc2k1 & DrM (drmalte@maltemedia.de)
// jedoch leicht verändert ;)


function replace_small_abc(input) {
    output_str = input.replace(/a/g, 'x');
    output_str = output_str.replace(/b/g, 'y');
    output_str = output_str.replace(/c/g, 'z');
    output_str = output_str.replace(/A/g, 'a');
    output_str = output_str.replace(/B/g, 'b');
    output_str = output_str.replace(/C/g, 'c');
    output_str = output_str.replace(/x/g, 'A');
    output_str = output_str.replace(/y/g, 'B');
    output_str = output_str.replace(/z/g, 'C');
    return output_str
}

function calculate() {
    var form = document.Windungsrechner;
    Slots = eval(form.Slots.value);
    Pole = eval(form.Pole.value);
    checkSingleLayerPossibility(false)
    // switchSingleLayer(); //这里使用全局变量，没有返回值
    if (Slots % 3 !== 0 || Slots < 3) {
        document.getElementById('Ergebnis').innerHTML = lang['nut_3_teilbar_' + selected_lang];
        document.Windungsrechner.Slots.focus();
        document.Windungsrechner.Slots.select();
        blink(document.Windungsrechner.Slots.id);
        clear();
        return;
    }

    if (Pole % 2 !== 0 || Pole < 2) {
        document.getElementById('Ergebnis').innerHTML = lang['pol_grade_' + selected_lang];
        document.Windungsrechner.Pole.focus();
        document.Windungsrechner.Pole.select();
        blink(document.Windungsrechner.Pole.id);
        clear();
        return;
    }

    if (Pole === Slots) {
        document.getElementById('Ergebnis').innerHTML = lang['nut_pol_ungleich_' + selected_lang];
        document.Windungsrechner.Pole.focus();
        document.Windungsrechner.Pole.select();
        blink(document.Windungsrechner.Pole.id);
        clear();
        return;
    }

    var number_of_slots_per_pole = Slots / 3 / Pole;

    if (number_of_slots_per_pole >= 1) {
        distributed = true;
    } else {
        distributed = false;
    }

    angle = 180 * Pole / Slots;
    a = 0;
    b = 0;
    c = 0;
    A = 0;
    B = 0;
    C = 0;
    m = 0;
    schema = ""
    sum = 0;
    if (!distributed) {
        //如果不是分布式绕组
        for (i = 0; i < Slots; i++) {
            if (i % 2 !== 0 && isSingleLayer) {
                schema += "-";
                m++;
            } else {
                if (sum >= 330 || sum < 30) {
                    schema += "A";
                    A++;
                }
                if (sum >= 30 && sum < 90) {
                    schema += "b";
                    b++;
                }
                if (sum >= 90 && sum < 150) {
                    schema += "C";
                    C++;
                }
                if (sum >= 150 && sum < 210) {
                    schema += "a";
                    a++;
                }
                if (sum >= 210 && sum < 270) {
                    schema += "B";
                    B++;
                }
                if (sum >= 270 && sum < 330) {
                    schema += "c";
                    c++;
                }
            }
            sum = (sum + angle) % 360;
        }
    } else {
        //如果是分布式绕组
        for (i = 0; i < Slots; i++) {
            if (sum >= 330 || sum < 30) {
                schema += "A";
                A++;
            }
            if (sum >= 30 && sum < 90) {
                schema += "b";
                b++;
            }
            if (sum >= 90 && sum < 150) {
                schema += "C";
                C++;
            }
            if (sum >= 150 && sum < 210) {
                schema += "a";
                a++;
            }
            if (sum >= 210 && sum < 270) {
                schema += "B";
                B++;
            }
            if (sum >= 270 && sum < 330) {
                schema += "c";
                c++;
            }
            schema += "|";
            sum = (sum + angle) % 360;
        }

    }

    inputIsValid = false;
    if (a === b && a === c && A === B && A === C && schema.indexOf('a') !== -1 && schema.indexOf('A') !== -1) {
        while (schema.charAt(schema.length - 1) === 'a' || schema.charAt(schema.length - 1) === 'A') {
            schema = schema.charAt(schema.length - 1) + schema.slice(0, -1);
        }
    }

    if (schema.charAt(0) === "a") {
        schema = replace_small_abc(schema)
    }

    if (schema.search(/[bB]/) > schema.search(/[cC]/)) {
        schema = schema.replace(/b/g, 'x');
        schema = schema.replace(/c/g, 'y');
        schema = schema.replace(/x/g, 'c');
        schema = schema.replace(/y/g, 'b');
        schema = schema.replace(/B/g, 'x');
        schema = schema.replace(/C/g, 'y');
        schema = schema.replace(/x/g, 'C');
        schema = schema.replace(/y/g, 'B');
    }
    //document.Windungsrechner.Ergebnis.value = schema;
    let secondlayer;
    let firstlayer;
    if (distributed) {
        distributed = schema;
        var slot_count = schema.split('|');
        schema = "";
        schema_y = "";
        for (i = 1; i < slot_count.length; i++) {
            schema = schema + "-";
            // schema_y = schema;
        }
        console.log(isSingleLayer);
        if (isSingleLayer) {
            console.log("is single layer");
            // schema = schema.replace(/\|/g, '').replace(/a/g, '').replace(/b/g, '').replace(/c/g, '');
            //console.log(schema)
            if (distributed.replace(/a/g, '').length === distributed.replace(/A/g, '').length && distributed.replace(/b/g, '').length === distributed.replace(/B/g, '').length && distributed.replace(/c/g, '').length === distributed.replace(/C/g, '').length) {

                if (a !== b || a !== c || A !== B || A !== C) {
                    Schema_output(Slots, Pole, schema, lang['unausgewogen_' + selected_lang], false, schema);
                } else {
                    Schema_output(Slots, Pole, schema, false, false, schema);
                }
            } else {
                Schema_output(Slots, Pole, schema, lang['unausgewogen_' + selected_lang], false, schema);
            }
        } else {
            console.log("winding has double layers");
            // schema = schema.replace(/\|/g, '').replace(/a/g, '').replace(/b/g, '').replace(/c/g, '');
            //console.log(schema)
            let layer2 = distributed;
            firstlayer = distributed.replace(/\|/g, '').split('').join("");
            console.log("first layer :  " + firstlayer);
            secondlayer = layer2.replace(/\|/g, '').split('').join("");
            console.log("second layer before shift:  " + secondlayer);
            let shorteningValue = document.getElementById('verkuerzung').value;
            secondlayer = shiftcycle(secondlayer, shorteningValue);
            secondlayer = replace_small_abc(secondlayer);
            console.log("second layer after shift:   " + secondlayer);
            let bothlayers = "";
            for (i = 0; i < Slots; i++) {
                bothlayers += firstlayer[i] + secondlayer[i] + '|';
            }
            console.log(bothlayers);
            isFractionalDistributed = false;
            if (distributed.replace(/a/g, '').length === distributed.replace(/A/g, '').length && distributed.replace(/b/g, '').length === distributed.replace(/B/g, '').length && distributed.replace(/c/g, '').length === distributed.replace(/C/g, '').length) {

                if (a !== b || a !== c || A !== B || A !== C) {
                    Schema_output(Slots, Pole, schema, lang['unausgewogen_' + selected_lang], false, schema, false);
                } else {
                    Schema_output(Slots, Pole, schema, false, false, schema, false);
                }
            } else if (bothlayers.replace(/a/g, '').length === bothlayers.replace(/A/g, '').length && bothlayers.replace(/b/g, '').length === bothlayers.replace(/B/g, '').length && bothlayers.replace(/c/g, '').length === bothlayers.replace(/C/g, '').length) {
                isFractionalDistributed = true;
                Schema_output(Slots, Pole, schema, false, false, schema, bothlayers);
            } else {
                console.log(a);
                console.log(b);
                console.log(c);
                console.log(A);
                console.log(B);
                console.log(C);
                Schema_output(Slots, Pole, schema, lang['unausgewogen_' + selected_lang], false, schema, false);
            }
        }

    } else {
        if (a !== b || a !== c || A !== B || A !== C) {
            Schema_output(Slots, Pole, schema, lang['unausgewogen_' + selected_lang], false, schema, false);
        } else {
            Schema_output(Slots, Pole, schema, false, false, schema, false);
        }
    }

}
